// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import { postAnswer } from "@/services/answer";
import type { NextApiRequest, NextApiResponse } from "next";

type Data = {
  errno: number;
  msg?: string;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function getAnswerInfo(reqBody: any) {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const answerList: any[] = [];
  Object.keys(reqBody).forEach((key) => {
    if (key === "questionId") return;
    answerList.push({
      componentId: key,
      value: reqBody[key],
    });
  });
  return {
    questionId: reqBody.questionId || "",
    answerList,
  };
}
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  if (req.method !== "POST") {
    res.status(200).json({ errno: -1, msg: "Method 错误" });
  }
  const answerInfo = getAnswerInfo(req.body);
  try {
    //提交到服务端 MOCK
    const resData = await postAnswer(answerInfo);
    if (resData.errno === 0) {
      res.redirect("/success");
      return 
    } else {
      res.redirect("/fail");
    }
  } catch {
    res.redirect("/fail");
  }
}
